package org.an.proj.contacts.db;

import android.database.sqlite.SQLiteDatabase;
import org.an.proj.contacts.MyApplication;
import org.an.proj.contacts.db.dao.DaoMaster;
import org.an.proj.contacts.db.dao.DaoSession;

/**
 * 创建时间：2016年11月03日10:31 <br>
 * 作者：fuchaoyang <br>
 * 描述：
 */

public class DBManager {

  // 是否加密  
  public static final boolean ENCRYPTED = true;

  private static final String DB_NAME = "contacts.db";
  // 是不是这样可以创建多张表
  private static final String DB_NAME2 = "test.db";
  private static DBManager mDBManager;
  private static DaoMaster.DevOpenHelper mDevOpenHelper;
  private static DaoMaster mDaoMaster;
  private static DaoSession mDaoSession;

  private DBManager() {
    // 初始化数据库信息
    mDevOpenHelper = new DaoMaster.DevOpenHelper(MyApplication.getInstance(), DB_NAME);
    getDaoMaster();
    getDaoSession();
  }

  public static DBManager getInstance() {
    if (null == mDBManager) {
      synchronized (DBManager.class) {
        if (null == mDBManager) {
          mDBManager = new DBManager();
        }
      }
    }
    return mDBManager;
  }

  /**
   * @desc 获取可读数据库
   **/
  public static SQLiteDatabase getReadableDatabase() {
    if (null == mDevOpenHelper) {
      getInstance();
    }
    return mDevOpenHelper.getReadableDatabase();
  }

  /**
   * @desc 获取可写数据库
   **/
  public static SQLiteDatabase getWritableDatabase() {
    if (null == mDevOpenHelper) {
      getInstance();
    }
    return mDevOpenHelper.getWritableDatabase();
  }

  /**
   * @desc 获取DaoMaster
   **/
  public static DaoMaster getDaoMaster() {
    if (null == mDaoMaster) {
      synchronized (DBManager.class) {
        if (null == mDaoMaster) {
          mDaoMaster = new DaoMaster(getWritableDatabase());
        }
      }
    }
    return mDaoMaster;
  }

  /**
   * @desc 获取DaoSession
   **/
  public static DaoSession getDaoSession() {
    if (null == mDaoSession) {
      synchronized (DBManager.class) {
        mDaoSession = getDaoMaster().newSession();
      }
    }

    return mDaoSession;
  }
} 
